﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OnlineEducation.Controllers;
using OnlineEducation.Data;
using OnlineEducation.Data.Entities;
using OnlineEducation.Extensions;
using OnlineEducation.Helpers;
using OnlineEducation.Models.OrderViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace OnlineEducation.Areas.Order.Controllers
{
    [Area("Order")]
    [Route("[controller]/[action]")]
    [Authorize(Roles = "Student")]
    public class OrderController : BaseController
    {
        private readonly ILogger _logger;
        private readonly ApplicationDbContext _context;
        private readonly IWebHostEnvironment _env;

        public OrderController(ApplicationDbContext context, ILogger<OrderController> logger, IWebHostEnvironment env)
        {
            _context = context;
            _logger = logger;
            _env = env;

        }
        public async Task<IActionResult> Index()
        {
            var studentId = User.GetUserID();
            var viewModel = new OrderCourseViewModel();
            viewModel.Bookings = await _context.Bookings.Include(r => r.TeachingPlan).ThenInclude(r => r.TeachingPlanItems).ThenInclude(r => r.Lesson)
                                                .Include(r => r.TeachingPlan).ThenInclude(r => r.Course).ThenInclude(r => r.Teacher)
                                                .Where(r => r.StudentId == studentId && r.TeachingPlan.Category == 1).ToListAsync();


            viewModel.NeedPay = viewModel.Bookings.Where(r => r.Status == 0).ToList(); // 未支付
            viewModel.PreTeachings = viewModel.Bookings.Where(r => (r.Status == 1 && r.TeachingPlan.BeginTime > DateTime.Today)).ToList(); // 待授课： 已经支付但是上课的时间还未到
            viewModel.Teachings = viewModel.Bookings.Where(r => r.Status == 1 && r.TeachingPlan.BeginTime <= DateTime.Today && r.TeachingPlan.EndTime >= DateTime.Today).ToList();// 正在授课 已经支付，但是已经在授课期间
            viewModel.TeachDone = viewModel.Bookings.Where(r => r.Status == 1 && r.TeachingPlan.EndTime < DateTime.Today).ToList();
            viewModel.TeachingEvaluationViewModels = _context.CourseEvaluations.Where(r => r.StudentId == studentId).Include(r => r.Student).Include(r => r.TeachingPlan).ThenInclude(r => r.Course).Select(r => new TeachingEvaluationViewModel
            {
                Content = r.Content,
                Point = r.Point,
                CourseName = r.TeachingPlan.Course.Title,
                StudentName = r.Student.FullName,
                StudentId = r.StudentId,
                TeachPlanId = r.TeachingPlanId,
                Id = r.Id
            }).ToList();
            return View(viewModel);
        }

        //[HttpPost]
        //public async Task<IActionResult> Delete(int id)
        //{
        //    var bookinginfo = await _context.Bookings.FindAsync(id);
        //    if (bookinginfo != null)
        //    {
        //        _context.Bookings.Remove(bookinginfo);
        //        await _context.SaveChangesAsync();
        //    }
        //    return Json(new { success = true, message = "更新数据成功.", data = id });
        //}

        /// <summary>
        /// Adds the teaching evaluation.
        /// </summary>
        /// <param name="teachingEvaluationViewModel">The teaching evaluation view model.</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddTeachingEvaluation(TeachingEvaluationViewModel teachingEvaluationViewModel)
        {
            try
            {
                var isAdd = false;
                var evaluation = await _context.CourseEvaluations.FindAsync(teachingEvaluationViewModel.Id);
                if (evaluation == null)
                {
                    isAdd = true;
                    evaluation = new TeachingEvaluation();
                }
                evaluation.Content = teachingEvaluationViewModel.Content;
                evaluation.Point = teachingEvaluationViewModel.Point;
                evaluation.StudentId = User.GetUserID();
                evaluation.TeachingPlanId = teachingEvaluationViewModel.TeachPlanId;
                if (isAdd)
                    _context.Add(evaluation);
                else
                {
                    evaluation.UpdatedBy = HttpContextHelper.Current.User.Identity.Name;
                    evaluation.UpdatedTime = DateTime.Now;
                    _context.Update(evaluation);

                }

                await _context.SaveChangesAsync();

                return Json(new { success = true, message = "新增评价成功.", data = evaluation.Id });
            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// Adds the Evaluation.
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> AddEvaluation(int? id, int? teachplanId)
        {
            TeachingEvaluationViewModel teachingEvaluationViewModels = new TeachingEvaluationViewModel();
            if (id.HasValue)
            {
                var evaluation = await _context.CourseEvaluations.Include(r => r.Student).Include(r => r.TeachingPlan).ThenInclude(r => r.Course).FirstOrDefaultAsync(r => r.Id == id.Value);
                teachingEvaluationViewModels.Point = evaluation.Point;
                teachingEvaluationViewModels.StudentId = evaluation.StudentId;
                teachingEvaluationViewModels.StudentName = evaluation.Student.FullName;
                teachingEvaluationViewModels.TeachPlanId = evaluation.TeachingPlanId;
                teachingEvaluationViewModels.CourseName = evaluation.TeachingPlan.Course.Title;
                teachingEvaluationViewModels.Content = evaluation.Content;
                teachingEvaluationViewModels.Id = evaluation.Id;
            }
            else
            {
                teachingEvaluationViewModels.TeachPlanId = teachplanId.HasValue ? teachplanId.Value : 0;
            }

            return View("AddEvaluation", teachingEvaluationViewModels);
        }
    }
}
